package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manuscript-service/models/cache"
	"manuscript-service/models/mysql"
	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceListLogic {
	return &ServiceListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ServiceListLogic) ServiceList(in *servicerpc.ServiceListRequest) (*servicerpc.ServiceListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("list_")
	var list []*servicerpc.ServiceList
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		list = mysql.ServiceList(mysql.DB, list)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &servicerpc.ServiceListResponse{
		List: list,
	}, nil
}
